﻿

using LeaderCCSLaserUI.Data;
using LeaderCCSLaserUI.Data.Extensions;
using LeaderCCSLaserUI.Models;
using LeaderCCSLaserUI.Services;
using MotionRobot.Models;
using Newtonsoft.Json;
using NLog;
using Prism.Commands;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MessageBox = System.Windows.Forms.MessageBox;

namespace LeaderCCSLaserUI.ViewModels.Dialogs
{
    public class AxisDialogViewModel : DialogViewModel
    {
        #region 变量
        private readonly IGTSCardService gTSCard;
        private readonly IServoModbusService servoModbus;
        private CancellationTokenSource source0, source1;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private Param? systemParam;
        private double mz1SafePos, mz2SafePos, mxYJogSpeed, mzJogSpeed;
        private bool isJogButtonPressing = false, isPrtMoving = false;
        #endregion
        #region 属性
        private ObservableCollection<AxisStatusDisp> axisStatusDisps;        
        public ObservableCollection<AxisStatusDisp> AxisStatusDisps
        {
            get { return axisStatusDisps; }
            set { SetProperty(ref axisStatusDisps, value); }
        }
        private ObservableCollection<bool> eXI;
        public ObservableCollection<bool> EXI
        {
            get { return eXI; }
            set { SetProperty(ref eXI, value); }
        }
        private ObservableCollection<bool> eXO;
        public ObservableCollection<bool> EXO
        {
            get { return eXO; }
            set { SetProperty(ref eXO, value); }
        }
        private string xYJogSpeed;
        public string XYJogSpeed
        {
            get { return xYJogSpeed; }
            set { SetProperty(ref xYJogSpeed, value); }
        }
        private string zJogSpeed;
        public string ZJogSpeed
        {
            get { return zJogSpeed; }
            set { SetProperty(ref zJogSpeed, value); }
        }
        private string xYRunSpeed;
        public string XYRunSpeed
        {
            get { return xYRunSpeed; }
            set { SetProperty(ref xYRunSpeed, value); }
        }
        private string zRunSpeed;
        public string ZRunSpeed
        {
            get { return zRunSpeed; }
            set { SetProperty(ref zRunSpeed, value); }
        }
        private double z1Abs;
        public double Z1Abs
        {
            get { return z1Abs; }
            set { SetProperty(ref z1Abs, value); }
        }
        private double z2Abs;
        public double Z2Abs
        {
            get { return z2Abs; }
            set { SetProperty(ref z2Abs, value); }
        }
        private string z1SafePos;
        public string Z1SafePos
        {
            get { return z1SafePos; }
            set { SetProperty(ref z1SafePos, value); }
        }
        private string z2SafePos;
        public string Z2SafePos
        {
            get { return z2SafePos; }
            set { SetProperty(ref z2SafePos, value); }
        }

        private bool isBusy;
        public bool IsBusy
        {
            get { return isBusy; }
            set { SetProperty(ref isBusy, value); }
        }
        private double testPoint_X;
        public double TestPoint_X
        {
            get { return testPoint_X; }
            set { SetProperty(ref testPoint_X, value); }
        }
        private double testPoint_Y;
        public double TestPoint_Y
        {
            get { return testPoint_Y; }
            set { SetProperty(ref testPoint_Y, value); }
        }
        private double testPoint_Z;
        public double TestPoint_Z
        {
            get { return testPoint_Z; }
            set { SetProperty(ref testPoint_Z, value); }
        }
        private double testPoint_X1;
        public double TestPoint_X1
        {
            get { return testPoint_X1; }
            set { SetProperty(ref testPoint_X1, value); }
        }
        private double testPoint_Y1;
        public double TestPoint_Y1
        {
            get { return testPoint_Y1; }
            set { SetProperty(ref testPoint_Y1, value); }
        }
        private double testPoint_Z1;
        public double TestPoint_Z1
        {
            get { return testPoint_Z1; }
            set { SetProperty(ref testPoint_Z1, value); }
        }
        private ObservableCollection<AxisNormalPointDisp> normalPointList1;
        public ObservableCollection<AxisNormalPointDisp> NormalPointList1
        {
            get { return normalPointList1; }
            set { SetProperty(ref normalPointList1, value); }
        }
        private ObservableCollection<AxisNormalPointDisp> normalPointList2;
        public ObservableCollection<AxisNormalPointDisp> NormalPointList2
        {
            get { return normalPointList2; }
            set { SetProperty(ref normalPointList2, value); }
        }
        private double leftAuxiliaryPosEnc;
        public double LeftAuxiliaryPosEnc
        {
            get { return leftAuxiliaryPosEnc; }
            set { SetProperty(ref leftAuxiliaryPosEnc, value); }
        }
        private double leftPowerValue;
        public double LeftPowerValue
        {
            get { return leftPowerValue; }
            set { SetProperty(ref leftPowerValue, value); }
        }
        private double rightAuxiliaryPosEnc;
        public double RightAuxiliaryPosEnc
        {
            get { return rightAuxiliaryPosEnc; }
            set { SetProperty(ref rightAuxiliaryPosEnc, value); }
        }
        private double rightPowerValue;
        public double RightPowerValue
        {
            get { return rightPowerValue; }
            set { SetProperty(ref rightPowerValue, value); }
        }
        private string lineScanSpeed;
        public string LineScanSpeed
        {
            get { return lineScanSpeed; }
            set { SetProperty(ref lineScanSpeed, value); }
        }
        private double jogDist;
        public double JogDist
        {
            get { return jogDist; }
            set {
                if (value > 0 && value <10)
                {
                    SetProperty(ref jogDist, value);
                }
            }
        }
        private string z1UpDist;
        public string Z1UpDist
        {
            get { return z1UpDist; }
            set { SetProperty(ref z1UpDist, value); }
        }
        private string z2UpDist;
        public string Z2UpDist
        {
            get { return z2UpDist; }
            set { SetProperty(ref z2UpDist, value); }
        }
        private string xMinDist;
        public string XMinDist
        {
            get { return xMinDist; }
            set { SetProperty(ref xMinDist, value); }
        }
        #endregion
        #region 命令
        private DelegateCommand<object> clearAlarmCommand;
        public DelegateCommand<object> ClearAlarmCommand =>
            clearAlarmCommand ?? (clearAlarmCommand = new DelegateCommand<object>(ExecuteClearAlarmCommand));
        private DelegateCommand<object> servoOnCommand;
        public DelegateCommand<object> ServoOnCommand =>
            servoOnCommand ?? (servoOnCommand = new DelegateCommand<object>(ExecuteServoOnCommand));
        private DelegateCommand<object> iOOutCommand;
        public DelegateCommand<object> IOOutCommand =>
            iOOutCommand ?? (iOOutCommand = new DelegateCommand<object>(ExecuteIOOutCommand));
        private DelegateCommand<object> textBoxLostFocusCommand;
        public DelegateCommand<object> TextBoxLostFocusCommand =>
            textBoxLostFocusCommand ?? (textBoxLostFocusCommand = new DelegateCommand<object>(ExecuteTextBoxLostFocusCommand));

        private DelegateCommand<object> getAbsCommand;
        public DelegateCommand<object> GetAbsCommand =>
            getAbsCommand ?? (getAbsCommand = new DelegateCommand<object>(ExecuteGetAbsCommand));
        private DelegateCommand<object> jog_MouseDownCommand;
        public DelegateCommand<object> Jog_MouseDownCommand =>
            jog_MouseDownCommand ?? (jog_MouseDownCommand = new DelegateCommand<object>(ExecuteJog_MouseDownCommand));
        private DelegateCommand jog_MouseUpCommand;
        public DelegateCommand Jog_MouseUpCommand =>
            jog_MouseUpCommand ?? (jog_MouseUpCommand = new DelegateCommand(ExecuteJog_MouseUpCommand));
        private DelegateCommand testPointGetCommand;
        public DelegateCommand TestPointGetCommand =>
            testPointGetCommand ?? (testPointGetCommand = new DelegateCommand(ExecuteTestPointGetCommand));
        private DelegateCommand testPointJumpCommand;
        public DelegateCommand TestPointJumpCommand =>
            testPointJumpCommand ?? (testPointJumpCommand = new DelegateCommand(ExecuteTestPointJumpCommand));
        private DelegateCommand testPointGoCommand;
        public DelegateCommand TestPointGoCommand =>
            testPointGoCommand ?? (testPointGoCommand = new DelegateCommand(ExecuteTestPointGoCommand));
        private DelegateCommand testPointGetCommand1;
        public DelegateCommand TestPointGetCommand1 =>
            testPointGetCommand1 ?? (testPointGetCommand1 = new DelegateCommand(ExecuteTestPointGetCommand1));
        private DelegateCommand testPointJumpCommand1;
        public DelegateCommand TestPointJumpCommand1 =>
            testPointJumpCommand1 ?? (testPointJumpCommand1 = new DelegateCommand(ExecuteTestPointJumpCommand1));
        private DelegateCommand testPointGoCommand1;
        public DelegateCommand TestPointGoCommand1 =>
            testPointGoCommand1 ?? (testPointGoCommand1 = new DelegateCommand(ExecuteTestPointGoCommand1));

        private DelegateCommand<object> safePosGoPosCommand;
        public DelegateCommand<object> SafePosGoPosCommand =>
            safePosGoPosCommand ?? (safePosGoPosCommand = new DelegateCommand<object>(ExecuteSafePosGoPosCommand));
        private DelegateCommand<object> teachNormalPointCommand;
        public DelegateCommand<object> TeachNormalPointCommand =>
            teachNormalPointCommand ?? (teachNormalPointCommand = new DelegateCommand<object>(ExecuteTeachNormalPointCommand));
        private DelegateCommand<object> jumpNormalPointCommand;
        public DelegateCommand<object> JumpNormalPointCommand =>
            jumpNormalPointCommand ?? (jumpNormalPointCommand = new DelegateCommand<object>(ExecuteJumpNormalPointCommand));
        private DelegateCommand<object> goNormalPointCommand;
        public DelegateCommand<object> GoNormalPointCommand =>
            goNormalPointCommand ?? (goNormalPointCommand = new DelegateCommand<object>(ExecuteGoNormalPointCommand));
        private DelegateCommand<object> teachNormalPoint2Command;
        public DelegateCommand<object> TeachNormalPoint2Command =>
            teachNormalPoint2Command ?? (teachNormalPoint2Command = new DelegateCommand<object>(ExecuteTeachNormalPoint2Command));
        private DelegateCommand<object> jumpNormalPoint2Command;
        public DelegateCommand<object> JumpNormalPoint2Command =>
            jumpNormalPoint2Command ?? (jumpNormalPoint2Command = new DelegateCommand<object>(ExecuteJumpNormalPoint2Command));
        private DelegateCommand<object> goNormalPoint2Command;
        public DelegateCommand<object> GoNormalPoint2Command =>
            goNormalPoint2Command ?? (goNormalPoint2Command = new DelegateCommand<object>(ExecuteGoNormalPoint2Command));
        private DelegateCommand leftGrabTriggerCommand;
        public DelegateCommand LeftGrabTriggerCommand =>
            leftGrabTriggerCommand ?? (leftGrabTriggerCommand = new DelegateCommand(ExecuteLeftGrabTriggerCommand));
        private DelegateCommand rightGrabTriggerCommand;
        public DelegateCommand RightGrabTriggerCommand =>
            rightGrabTriggerCommand ?? (rightGrabTriggerCommand = new DelegateCommand(ExecuteRightGrabTriggerCommand));

        void ExecuteRightGrabTriggerCommand()
        {
            if (gTSCard.Connected)
            {
                GTSCard.ComparePulseTrigger(0, 2);
            }
        }
        void ExecuteLeftGrabTriggerCommand()
        {
            if (gTSCard.Connected)
            {
                GTSCard.ComparePulseTrigger(0, 1);
            }
        }
        async void ExecuteGoNormalPoint2Command(object obj)
        {
            if (obj is AxisNormalPointDisp point)
            {
                if (MessageBox.Show($"确认Go运动到\"{point.Name}\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    IsBusy = true;
                    GTSCard.ServoOn(gTSCard.A5);//X
                    GTSCard.ServoOn(gTSCard.A6);//Y
                    GTSCard.ServoOn(gTSCard.A7);//Z
                    GTSCard.AxisPosSet(gTSCard.A5, GTSCard.GetEnc(gTSCard.A5));
                    GTSCard.AxisPosSet(gTSCard.A6, GTSCard.GetEnc(gTSCard.A6));
                    GTSCard.AxisPosSet(gTSCard.A7, GTSCard.GetEnc(gTSCard.A7));
                    source1 = new CancellationTokenSource();
                    CancellationToken token = source1.Token;
                    await Task.Run(() => GoAction(token, point.X, point.Y, point.Z, gTSCard.A5, gTSCard.A6, gTSCard.A7), token).ContinueWith(t => { IsBusy = false; });
                }
            }
        }
        async void ExecuteJumpNormalPoint2Command(object obj)
        {
            if (obj is AxisNormalPointDisp point)
            {
                if (MessageBox.Show($"确认Jump运动到\"{point.Name}\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    IsBusy = true;
                    GTSCard.ServoOn(gTSCard.A5);//X
                    GTSCard.ServoOn(gTSCard.A6);//Y
                    GTSCard.ServoOn(gTSCard.A7);//Z
                    GTSCard.AxisPosSet(gTSCard.A5, GTSCard.GetEnc(gTSCard.A5));
                    GTSCard.AxisPosSet(gTSCard.A6, GTSCard.GetEnc(gTSCard.A6));
                    GTSCard.AxisPosSet(gTSCard.A7, GTSCard.GetEnc(gTSCard.A7));
                    source1 = new CancellationTokenSource();
                    CancellationToken token = source1.Token;
                    await Task.Run(() => JumpAction(token, point.X, point.Y, point.Z, gTSCard.A5, gTSCard.A6, gTSCard.A7, mz2SafePos), token).ContinueWith(t => { IsBusy = false; });
                }
            }
        }
        void ExecuteTeachNormalPoint2Command(object obj)
        {
            if (obj is AxisNormalPointDisp point)
            {
                if (MessageBox.Show($"确认示教\"{point.Name}\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                    switch (point.Name)
                    {
                        case "初始点":
                            {
                                var _pointParam = mdb.MParams.FirstOrDefault(param => param.Hand == 1 && param.Name == "PointInit");
                                if (_pointParam != null)
                                {
                                    var _point = JsonConvert.DeserializeObject<MPoint>(_pointParam.Value);
                                    point.X = _point.X = Math.Round(GTSCard.GetEnc(gTSCard.A5), 3);
                                    point.Y = _point.Y = Math.Round(GTSCard.GetEnc(gTSCard.A6), 3);
                                    point.Z = _point.Z = Math.Round(GTSCard.GetEnc(gTSCard.A7), 3);
                                    _pointParam.Value = JsonConvert.SerializeObject(_point, Formatting.Indented);
                                    mdb.SaveChanges();
                                }
                            }
                            break;
                      
                        case "相机标定点-拍照":
                            {
                                point.X = systemParam.RightCameraCalib.X = Math.Round(GTSCard.GetEnc(gTSCard.A5), 3);
                                point.Y = systemParam.RightCameraCalib.Y = Math.Round(GTSCard.GetEnc(gTSCard.A6), 3);
                                point.Z = systemParam.RightCameraCalib.Z = Math.Round(GTSCard.GetEnc(gTSCard.A7), 3);
                                SavedParam();
                            }
                            break;
                        case "相机标定点-焊接":
                            {
                                point.X = systemParam.RightCameraCalibLazer.X = Math.Round(GTSCard.GetEnc(gTSCard.A5), 3);
                                point.Y = systemParam.RightCameraCalibLazer.Y = Math.Round(GTSCard.GetEnc(gTSCard.A6), 3);
                                point.Z = systemParam.RightCameraCalibLazer.Z = Math.Round(GTSCard.GetEnc(gTSCard.A7), 3);
                                SavedParam();
                            }
                            break;
                       
                        default:
                            break;
                    }
                }
            }
        }
        async void ExecuteGoNormalPointCommand(object obj)
        {
            if (obj is AxisNormalPointDisp point)
            {
                if (MessageBox.Show($"确认Go运动到\"{point.Name}\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    IsBusy = true;
                    GTSCard.ServoOn(gTSCard.A1);//X
                    GTSCard.ServoOn(gTSCard.A2);//Y
                    GTSCard.ServoOn(gTSCard.A3);//Z
                    GTSCard.AxisPosSet(gTSCard.A1, GTSCard.GetEnc(gTSCard.A1));
                    GTSCard.AxisPosSet(gTSCard.A2, GTSCard.GetEnc(gTSCard.A2));
                    GTSCard.AxisPosSet(gTSCard.A3, GTSCard.GetEnc(gTSCard.A3));
                    source1 = new CancellationTokenSource();
                    CancellationToken token = source1.Token;
                    await Task.Run(() => GoAction(token, point.X, point.Y, point.Z, gTSCard.A1, gTSCard.A2, gTSCard.A3), token).ContinueWith(t => { IsBusy = false; });
                }
            }
        }
        async void ExecuteJumpNormalPointCommand(object obj)
        {
            if (obj is AxisNormalPointDisp point)
            {
                if (MessageBox.Show($"确认Jump运动到\"{point.Name}\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    IsBusy = true;
                    GTSCard.ServoOn(gTSCard.A1);//X
                    GTSCard.ServoOn(gTSCard.A2);//Y
                    GTSCard.ServoOn(gTSCard.A3);//Z
                    GTSCard.AxisPosSet(gTSCard.A1, GTSCard.GetEnc(gTSCard.A1));
                    GTSCard.AxisPosSet(gTSCard.A2, GTSCard.GetEnc(gTSCard.A2));
                    GTSCard.AxisPosSet(gTSCard.A3, GTSCard.GetEnc(gTSCard.A3));
                    source1 = new CancellationTokenSource();
                    CancellationToken token = source1.Token;
                    await Task.Run(() => JumpAction(token, point.X, point.Y, point.Z, gTSCard.A1, gTSCard.A2, gTSCard.A3, mz1SafePos), token).ContinueWith(t => { IsBusy = false; });
                }
            }
        }
        void ExecuteTeachNormalPointCommand(object obj)
        {
            if (obj is AxisNormalPointDisp point)
            {
                if (MessageBox.Show($"确认示教\"{point.Name}\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                    switch (point.Name)
                    {
                        case "初始点":
                            {
                                var _pointParam = mdb.MParams.FirstOrDefault(param => param.Hand == 0 && param.Name == "PointInit");
                                if (_pointParam != null)
                                {
                                    var _point = JsonConvert.DeserializeObject<MPoint>(_pointParam.Value);
                                    point.X = _point.X = Math.Round(GTSCard.GetEnc(gTSCard.A1), 3);
                                    point.Y = _point.Y = Math.Round(GTSCard.GetEnc(gTSCard.A2), 3);
                                    point.Z = _point.Z = Math.Round(GTSCard.GetEnc(gTSCard.A3), 3);
                                    _pointParam.Value = JsonConvert.SerializeObject(_point, Formatting.Indented);
                                    mdb.SaveChanges();
                                }
                            }
                            break;
                        case "相机标定点-拍照":
                            {
                                point.X = systemParam.LeftCameraCalib.X = Math.Round(GTSCard.GetEnc(gTSCard.A1), 3);
                                point.Y = systemParam.LeftCameraCalib.Y = Math.Round(GTSCard.GetEnc(gTSCard.A2), 3);
                                point.Z = systemParam.LeftCameraCalib.Z = Math.Round(GTSCard.GetEnc(gTSCard.A3), 3);
                                SavedParam();
                            }
                            break;
                        case "相机标定点-焊接":
                            {
                                point.X = systemParam.LeftCameraCalibLazer.X = Math.Round(GTSCard.GetEnc(gTSCard.A1), 3);
                                point.Y = systemParam.LeftCameraCalibLazer.Y = Math.Round(GTSCard.GetEnc(gTSCard.A2), 3);
                                point.Z = systemParam.LeftCameraCalibLazer.Z = Math.Round(GTSCard.GetEnc(gTSCard.A3), 3);
                                SavedParam();
                            }
                            break;
                        
                        default:
                            break;
                    }
                }
            }
        }
        async void ExecuteSafePosGoPosCommand(object obj)
        {
            if (MessageBox.Show($"确认Go运动到\"Z安全位\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                switch (obj.ToString())
                {
                    case "0":
                        {
                            IsBusy = true;
                            GTSCard.ServoOn(gTSCard.A1);//X
                            GTSCard.ServoOn(gTSCard.A2);//Y
                            GTSCard.ServoOn(gTSCard.A3);//Z
                            GTSCard.AxisPosSet(gTSCard.A1, GTSCard.GetEnc(gTSCard.A1));
                            GTSCard.AxisPosSet(gTSCard.A2, GTSCard.GetEnc(gTSCard.A2));
                            GTSCard.AxisPosSet(gTSCard.A3, GTSCard.GetEnc(gTSCard.A3));
                            source1 = new CancellationTokenSource();
                            CancellationToken token = source1.Token;
                            var xcur = GTSCard.GetEnc(gTSCard.A1);
                            var ycur = GTSCard.GetEnc(gTSCard.A2);
                            await Task.Run(() => GoAction(token, xcur, ycur, mz1SafePos, gTSCard.A1, gTSCard.A2, gTSCard.A3), token).ContinueWith(t => { IsBusy = false; });
                        }
                        break;
                    case "1":
                        {
                            IsBusy = true;
                            GTSCard.ServoOn(gTSCard.A5);//X
                            GTSCard.ServoOn(gTSCard.A6);//Y
                            GTSCard.ServoOn(gTSCard.A7);//Z
                            GTSCard.AxisPosSet(gTSCard.A5, GTSCard.GetEnc(gTSCard.A5));
                            GTSCard.AxisPosSet(gTSCard.A6, GTSCard.GetEnc(gTSCard.A6));
                            GTSCard.AxisPosSet(gTSCard.A7, GTSCard.GetEnc(gTSCard.A7));
                            source1 = new CancellationTokenSource();
                            CancellationToken token = source1.Token;
                            var xcur = GTSCard.GetEnc(gTSCard.A5);
                            var ycur = GTSCard.GetEnc(gTSCard.A6);
                            await Task.Run(() => GoAction(token, xcur, ycur, mz2SafePos, gTSCard.A5, gTSCard.A6, gTSCard.A7), token).ContinueWith(t => { IsBusy = false; });
                        }
                        break;
                    default:
                        break;
                }

            }
        }
        async void ExecuteTestPointGoCommand1()
        {
            if (MessageBox.Show("确认Go运动到\"测试点\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                IsBusy = true;
                GTSCard.ServoOn(gTSCard.A5);//X
                GTSCard.ServoOn(gTSCard.A6);//Y
                GTSCard.ServoOn(gTSCard.A7);//Z
                GTSCard.AxisPosSet(gTSCard.A5, GTSCard.GetEnc(gTSCard.A5));
                GTSCard.AxisPosSet(gTSCard.A6, GTSCard.GetEnc(gTSCard.A6));
                GTSCard.AxisPosSet(gTSCard.A7, GTSCard.GetEnc(gTSCard.A7));
                source1 = new CancellationTokenSource();
                CancellationToken token = source1.Token;
                await Task.Run(() => GoAction(token, TestPoint_X1, TestPoint_Y1, TestPoint_Z1, gTSCard.A5, gTSCard.A6, gTSCard.A7), token).ContinueWith(t => { IsBusy = false; });
            }
        }
        async void ExecuteTestPointJumpCommand1()
        {
            if (MessageBox.Show("确认Jump运动到\"测试点\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                IsBusy = true;
                GTSCard.ServoOn(gTSCard.A5);//X
                GTSCard.ServoOn(gTSCard.A6);//Y
                GTSCard.ServoOn(gTSCard.A7);//Z
                GTSCard.AxisPosSet(gTSCard.A5, GTSCard.GetEnc(gTSCard.A5));
                GTSCard.AxisPosSet(gTSCard.A6, GTSCard.GetEnc(gTSCard.A6));
                GTSCard.AxisPosSet(gTSCard.A7, GTSCard.GetEnc(gTSCard.A7));
                source1 = new CancellationTokenSource();
                CancellationToken token = source1.Token;
                await Task.Run(() => JumpAction(token, TestPoint_X1, TestPoint_Y1, TestPoint_Z1, gTSCard.A5, gTSCard.A6, gTSCard.A7, mz2SafePos), token).ContinueWith(t => { IsBusy = false; });
            }
        }
        void ExecuteTestPointGetCommand1()
        {
            if (MessageBox.Show("确认示教当前位置到\"测试点\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                TestPoint_X1 = Math.Round(GTSCard.GetEnc(gTSCard.A5), 3);
                TestPoint_Y1 = Math.Round(GTSCard.GetEnc(gTSCard.A6), 3);
                TestPoint_Z1 = Math.Round(GTSCard.GetEnc(gTSCard.A7), 3);
            }
        }
        async void ExecuteTestPointGoCommand()
        {
            if (MessageBox.Show("确认Go运动到\"测试点\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                IsBusy = true;
                GTSCard.ServoOn(gTSCard.A1);//X
                GTSCard.ServoOn(gTSCard.A2);//Y
                GTSCard.ServoOn(gTSCard.A3);//Z
                GTSCard.AxisPosSet(gTSCard.A1, GTSCard.GetEnc(gTSCard.A1));
                GTSCard.AxisPosSet(gTSCard.A2, GTSCard.GetEnc(gTSCard.A2));
                GTSCard.AxisPosSet(gTSCard.A3, GTSCard.GetEnc(gTSCard.A3));
                source1 = new CancellationTokenSource();
                CancellationToken token = source1.Token;
                await Task.Run(() => GoAction(token, TestPoint_X, TestPoint_Y, TestPoint_Z, gTSCard.A1, gTSCard.A2, gTSCard.A3), token).ContinueWith(t => { IsBusy = false; });
            }
        }
        async void ExecuteTestPointJumpCommand()
        {
            if (MessageBox.Show("确认Jump运动到\"测试点\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                IsBusy = true;
                GTSCard.ServoOn(gTSCard.A1);//X
                GTSCard.ServoOn(gTSCard.A2);//Y
                GTSCard.ServoOn(gTSCard.A3);//Z
                GTSCard.AxisPosSet(gTSCard.A1, GTSCard.GetEnc(gTSCard.A1));
                GTSCard.AxisPosSet(gTSCard.A2, GTSCard.GetEnc(gTSCard.A2));
                GTSCard.AxisPosSet(gTSCard.A3, GTSCard.GetEnc(gTSCard.A3));
                source1 = new CancellationTokenSource();
                CancellationToken token = source1.Token;
                await Task.Run(() => JumpAction(token, TestPoint_X, TestPoint_Y, TestPoint_Z, gTSCard.A1, gTSCard.A2, gTSCard.A3, mz1SafePos), token).ContinueWith(t => { IsBusy = false; });
            }
        }
        void ExecuteTestPointGetCommand()
        {
            if (MessageBox.Show("确认示教当前位置到\"测试点\"吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                TestPoint_X = Math.Round(GTSCard.GetEnc(gTSCard.A1), 3);
                TestPoint_Y = Math.Round(GTSCard.GetEnc(gTSCard.A2), 3);
                TestPoint_Z = Math.Round(GTSCard.GetEnc(gTSCard.A3), 3);
            }
        }
        void ExecuteJog_MouseUpCommand()
        {
            isJogButtonPressing = false;
            if (!isPrtMoving)
            {
                GTSCard.AxisStop(gTSCard.A1, 1);
                GTSCard.AxisStop(gTSCard.A2, 1);
                GTSCard.AxisStop(gTSCard.A3, 1);
                GTSCard.AxisStop(gTSCard.A5, 1);
                GTSCard.AxisStop(gTSCard.A6, 1);
                GTSCard.AxisStop(gTSCard.A7, 1);
                if (source1 != null)
                {
                    source1.Cancel();
                }
                IsBusy= false;
            }
        }
        void ExecuteJog_MouseDownCommand(object obj)
        {
            int index = int.Parse(obj.ToString());
            int _index = (index - 1) / 2;
            int dir = index % 2 != 0 ? 1 : 0;
            isJogButtonPressing = true;
            if (!isPrtMoving && !IsBusy)
            {
                IsBusy = true;
                isPrtMoving = true;
                AxisParm _axis;
                double _speed;
                switch (_index)
                {
                    case 0:
                        _axis = gTSCard.A1;
                        _speed = mxYJogSpeed;
                        break;
                    case 1:
                        _axis = gTSCard.A2;
                        _speed = mxYJogSpeed;
                        break;
                    case 2:
                        _axis = gTSCard.A3;
                        _speed = mzJogSpeed;
                        break;
                    case 3:
                        _axis = gTSCard.A5;
                        _speed = mxYJogSpeed;
                        break;
                    case 4:
                        _axis = gTSCard.A6;
                        _speed = mxYJogSpeed;
                        break;
                    case 5:
                    default:
                        _axis = gTSCard.A7;
                        _speed = mzJogSpeed;
                        break;
                }
                var curPos = GTSCard.GetPos(_axis);
                double _tarPos = 0;
                if (dir == 1)
                {
                    _tarPos = curPos + JogDist;
                }
                else
                {
                    _tarPos = curPos - JogDist;
                }
                source1 = new CancellationTokenSource();
                CancellationToken token = source1.Token;
                Task.Run(() => GoAction(token, _axis, _tarPos, _speed), token).ContinueWith(arg => {

                    isPrtMoving = false;
                    if (isJogButtonPressing)
                    {
                        GTSCard.AxisJog(_axis, (ushort)dir, _speed);
                    }
                    else
                    {
                        IsBusy = false;
                    }
                });
            }
        }
        void ExecuteGetAbsCommand(object obj)
        {
            string zAxisName = obj.ToString() == "0" ? "Z1" : "Z2";
            if (servoModbus.Connected)
            {
                if (MessageBox.Show($"确定更新{zAxisName}吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    try
                    {
                        switch (obj.ToString())
                        {
                            case "0":
                                {
                                    int pls = servoModbus.ReadInovance(1);
                                    var pos = Math.Round(pls * gTSCard.A3.Equiv, 3);
                                    GTSCard.AxisPosSet(gTSCard.A3, 0);
                                    GTSCard.AxisEncSet(gTSCard.A3, 0);
                                    systemParam.Z1Abs = pos;
                                    Z1Abs = pos;
                                }
                                break;
                            case "1":
                                {
                                    int pls = servoModbus.ReadInovance(2);
                                    var pos = Math.Round(pls * gTSCard.A7.Equiv, 3);
                                    GTSCard.AxisPosSet(gTSCard.A7, 0);
                                    GTSCard.AxisEncSet(gTSCard.A7, 0);
                                    systemParam.Z2Abs = pos;
                                    Z2Abs = pos;
                                }
                                break;
                            default:
                                break;
                        }
                        SavedParam();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            
        }

        void ExecuteTextBoxLostFocusCommand(object obj)
        {
            try
            {
                using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                switch (obj.ToString())
                {
                    case "XYJogSpeed":
                        {
                            if (double.TryParse(XYJogSpeed, out var v))
                            {
                                mxYJogSpeed = v;
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "XYJogSpeed");
                                if (_mParam != null)
                                {
                                    _mParam.Value = XYJogSpeed;
                                }
                            }
                               
                        }
                        break;
                    case "ZJogSpeed":
                        {
                            if (double.TryParse(ZJogSpeed, out var v))
                            {
                                mzJogSpeed = v;
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZJogSpeed");
                                if (_mParam != null)
                                {
                                    _mParam.Value = ZJogSpeed;
                                }
                            }
                                
                        }
                        break;
                    case "XYRunSpeed":
                        {
                            if (double.TryParse(XYRunSpeed, out var v))
                            {
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "XYRunSpeed");
                                if (_mParam != null)
                                {
                                    _mParam.Value = XYRunSpeed;
                                }
                            }
                        }
                        break;
                    case "ZRunSpeed":
                        {
                            if (double.TryParse(ZRunSpeed, out var v))
                            {
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZRunSpeed");
                                if (_mParam != null)
                                {
                                    _mParam.Value = ZRunSpeed;
                                }
                            }
                        }
                        break;
                    case "LineScanSpeed":
                        {
                            if (double.TryParse(LineScanSpeed, out var v))
                            {
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "LineScanSpeed");
                                if (_mParam != null)
                                {
                                    _mParam.Value = LineScanSpeed;
                                }
                            }
                        }
                        break;
                    case "Z1SafePos":
                        {
                            if (double.TryParse(Z1SafePos, out var v))
                            {
                                mz1SafePos = v;
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZSafePos" && m.Hand == 0);
                                if (_mParam != null)
                                {
                                    _mParam.Value = Z1SafePos;
                                }
                            }
                        }
                        break;
                    case "Z2SafePos":
                        {
                            if (double.TryParse(Z2SafePos, out var v))
                            {
                                mz2SafePos = v;
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZSafePos" && m.Hand == 1);
                                if (_mParam != null)
                                {
                                    _mParam.Value = Z2SafePos;
                                }
                            }
                        }
                        break;
                    case "Z1UpDist":
                        {
                            if (double.TryParse(Z1UpDist, out var v))
                            {
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZUpDist" && m.Hand == 0);
                                if (_mParam != null)
                                {
                                    _mParam.Value = Z1UpDist;
                                }
                            }
                        }
                        break;
                    case "Z2UpDist":
                        {
                            if (double.TryParse(Z2UpDist, out var v))
                            {
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZUpDist" && m.Hand == 1);
                                if (_mParam != null)
                                {
                                    _mParam.Value = Z2UpDist;
                                }
                            }
                        }
                        break;
                    case "XMinDist":
                        {
                            if (double.TryParse(XMinDist, out var v))
                            {
                                var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "XMinDist");
                                if (_mParam != null)
                                {
                                    _mParam.Value = XMinDist;
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
                mdb.SaveChanges();
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

        }
        void ExecuteIOOutCommand(object obj)
        {
            GTSCard.SetDo(gTSCard.A1.CardNo, (short)int.Parse(obj.ToString()), (short)(EXO[int.Parse(obj.ToString())] ? 0 : 1));
        }
        async void ExecuteServoOnCommand(object obj)
        {
            switch (obj.ToString())
            {
                case "1":
                    {
                        if (AxisStatusDisps[0].ServoOnState)
                        {
                            GTSCard.ServoOff(gTSCard.A1);
                        }
                        else
                        {
                            GTSCard.ServoOn(gTSCard.A1);
                            GTSCard.AxisPosSet(gTSCard.A1, GTSCard.GetEnc(gTSCard.A1));
                        }
                    }
                    break;
                case "2":
                    {
                        if (AxisStatusDisps[1].ServoOnState)
                        {
                            GTSCard.ServoOff(gTSCard.A2);
                        }
                        else
                        {
                            GTSCard.ServoOn(gTSCard.A2);
                            GTSCard.AxisPosSet(gTSCard.A2, GTSCard.GetEnc(gTSCard.A2));
                        }
                    }
                    break;
                case "3":
                    {
                        if (AxisStatusDisps[2].ServoOnState)
                        {
                            GTSCard.ServoOff(gTSCard.A3);
                        }
                        else
                        {
                            GTSCard.ServoOn(gTSCard.A3);
                            await Task.Delay(1000);
                            GTSCard.AxisPosSet(gTSCard.A3, GTSCard.GetEnc(gTSCard.A3));
                        }
                    }
                    break;
                case "4":
                    {
                        if (AxisStatusDisps[3].ServoOnState)
                        {
                            GTSCard.ServoOff(gTSCard.A5);
                        }
                        else
                        {
                            GTSCard.ServoOn(gTSCard.A5);
                            GTSCard.AxisPosSet(gTSCard.A5, GTSCard.GetEnc(gTSCard.A5));
                        }
                    }
                    break;
                case "5":
                    {
                        if (AxisStatusDisps[4].ServoOnState)
                        {
                            GTSCard.ServoOff(gTSCard.A6);
                        }
                        else
                        {
                            GTSCard.ServoOn(gTSCard.A6);
                            GTSCard.AxisPosSet(gTSCard.A6, GTSCard.GetEnc(gTSCard.A6));
                        }
                    }
                    break;
                case "6":
                    {
                        if (AxisStatusDisps[5].ServoOnState)
                        {
                            GTSCard.ServoOff(gTSCard.A7);
                        }
                        else
                        {
                            GTSCard.ServoOn(gTSCard.A7);
                            await Task.Delay(1000);
                            GTSCard.AxisPosSet(gTSCard.A7, GTSCard.GetEnc(gTSCard.A7));
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        void ExecuteClearAlarmCommand(object obj)
        {
            switch (obj.ToString())
            {
                case "1":
                    GTSCard.ClearAlm(gTSCard.A1);
                    break;
                case "2":
                    GTSCard.ClearAlm(gTSCard.A2);
                    break;
                case "3":
                    GTSCard.ClearAlm(gTSCard.A3);
                    break;
                case "4":
                    GTSCard.ClearAlm(gTSCard.A5);
                    break;
                case "5":
                    GTSCard.ClearAlm(gTSCard.A6);
                    break;
                case "6":
                    GTSCard.ClearAlm(gTSCard.A7);
                    break;
                default:
                    break;
            }
        }
        #endregion
        #region 导航
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            Title = "轴调试";
            LoadParam();

            Z1Abs = systemParam.Z1Abs;
            Z2Abs = systemParam.Z2Abs;
            TestPoint_X = 0;
            TestPoint_Y = 0;
            TestPoint_Z = 0;
            TestPoint_X1 = 0;
            TestPoint_Y1 = 0;
            TestPoint_Z1 = 0;

            using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
            var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "XYJogSpeed");
            if (_mParam != null)
            {
                XYJogSpeed = _mParam.Value;
                mxYJogSpeed = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZJogSpeed");
            if (_mParam != null)
            {
                ZJogSpeed = _mParam.Value;
                mzJogSpeed = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "XYRunSpeed");
            if (_mParam != null)
            {
                XYRunSpeed = _mParam.Value;
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZRunSpeed");
            if (_mParam != null)
            {
                ZRunSpeed = _mParam.Value;
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "LineScanSpeed");
            if (_mParam != null)
            {
                LineScanSpeed = _mParam.Value;
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZSafePos" && m.Hand == 0);
            if (_mParam != null)
            {
                Z1SafePos = _mParam.Value;
                mz1SafePos = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZSafePos" && m.Hand == 1);
            if (_mParam != null)
            {
                Z2SafePos = _mParam.Value;
                mz2SafePos = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZUpDist" && m.Hand == 0);
            if (_mParam != null)
            {
                Z1UpDist = _mParam.Value;
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZUpDist" && m.Hand == 1);
            if (_mParam != null)
            {
                Z2UpDist = _mParam.Value;
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "XMinDist");
            if (_mParam != null)
            {
                XMinDist = _mParam.Value;
            }
            else
            {
                XMinDist = "0";
                mdb.MParams.Add(new MParam
                {
                    Name = "XMinDist",
                    Value = XMinDist,
                    Hand = 0,
                    Type = typeof(double).Name
                });
                mdb.SaveChanges();
            }
            NormalPointList1.Clear();
            var _pointParam = mdb.MParams.FirstOrDefault(m => m.Name == "PointInit" && m.Hand == 0);
            if (_pointParam != null)
            {
                var _point = JsonConvert.DeserializeObject<MPoint>(_pointParam.Value);
                NormalPointList1.Add(new AxisNormalPointDisp
                {
                    X = _point.X,
                    Y = _point.Y,
                    Z = _point.Z,
                    Name = "初始点",
                    Unit = "mm"
                });
            }
            NormalPointList1.Add(new AxisNormalPointDisp
            {
                X = systemParam.LeftCameraCalib.X,
                Y = systemParam.LeftCameraCalib.Y,
                Z = systemParam.LeftCameraCalib.Z,
                Name = "相机标定点-拍照",
                Unit = "mm"
            });
            NormalPointList1.Add(new AxisNormalPointDisp
            {
                X = systemParam.LeftCameraCalibLazer.X,
                Y = systemParam.LeftCameraCalibLazer.Y,
                Z = systemParam.LeftCameraCalibLazer.Z,
                Name = "相机标定点-焊接",
                Unit = "mm"
            });

           

            NormalPointList2.Clear();
            _pointParam = mdb.MParams.FirstOrDefault(m => m.Name == "PointInit" && m.Hand == 1);
            if (_pointParam != null)
            {
                var _point = JsonConvert.DeserializeObject<MPoint>(_pointParam.Value);
                NormalPointList2.Add(new AxisNormalPointDisp
                {
                    X = _point.X,
                    Y = _point.Y,
                    Z = _point.Z,
                    Name = "初始点",
                    Unit = "mm"
                });
            }

            
            NormalPointList2.Add(new AxisNormalPointDisp
            {
                X = systemParam.RightCameraCalib.X,
                Y = systemParam.RightCameraCalib.Y,
                Z = systemParam.RightCameraCalib.Z,
                Name = "相机标定点-拍照",
                Unit = "mm"
            });
            NormalPointList2.Add(new AxisNormalPointDisp
            {
                X = systemParam.RightCameraCalibLazer.X,
                Y = systemParam.RightCameraCalibLazer.Y,
                Z = systemParam.RightCameraCalibLazer.Z,
                Name = "相机标定点-焊接",
                Unit = "mm"
            });

           

            if (gTSCard.Connected)
            {
                source0 = new CancellationTokenSource();
                CancellationToken token = source0.Token;
                Task.Run(() => UpdateAction(token), token);
            }
        }
        public override void OnDialogClosed()
        {
            if (source0 != null)
            {
                source0.Cancel();
            }
            if (source1 != null)
            {
                source1.Cancel();
            }
            aggregator.SendMessage("ReloadParam", "Run");
        }
        #endregion
        #region 构造函数
        public AxisDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            JogDist = 1;
            gTSCard = containerProvider.Resolve<IGTSCardService>("GTSCard");
            servoModbus = containerProvider.Resolve<IServoModbusService>("ServoModbus");
            AxisStatusDisps = new ObservableCollection<AxisStatusDisp>();            
            for (int i = 0; i < 6; i++)
            {
                AxisStatusDisps.Add(new AxisStatusDisp());
            }
            EXI = new ObservableCollection<bool>();
            for (int i = 0; i < 16; i++)
            {
                EXI.Add(false);
            }
            EXO = new ObservableCollection<bool>();
            for (int i = 0; i < 16; i++)
            {
                EXO.Add(false);
            }

            NormalPointList1 = new ObservableCollection<AxisNormalPointDisp>();
            NormalPointList2 = new ObservableCollection<AxisNormalPointDisp>();
        }
        #endregion
        #region 功能函数
        private void UpdateAction(CancellationToken token)
        {
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                try
                {
                    //左X轴
                    AxisStatus astatus = GTSCard.GetAxisStatus(gTSCard.A1);
                    AxisStatusDisps[0].AlmState = astatus.FlagAlm;
                    AxisStatusDisps[0].HomeState = astatus.FlagHome;
                    AxisStatusDisps[0].PosLimitState = astatus.FlagPosLimit;
                    AxisStatusDisps[0].NeglimitState = astatus.FlagNeglimit;
                    AxisStatusDisps[0].ServoOnState = astatus.FlagServoOn;
                    AxisStatusDisps[0].MoveState = !astatus.FlagMoveEnd;
                    AxisStatusDisps[0].PosPrf = Math.Round(astatus.PrfPos, 3);
                    AxisStatusDisps[0].PosEnc = Math.Round(astatus.EncPos, 3);
                    //左Y轴
                    astatus = GTSCard.GetAxisStatus(gTSCard.A2);
                    AxisStatusDisps[1].AlmState = astatus.FlagAlm;
                    AxisStatusDisps[1].HomeState = astatus.FlagHome;
                    AxisStatusDisps[1].PosLimitState = astatus.FlagPosLimit;
                    AxisStatusDisps[1].NeglimitState = astatus.FlagNeglimit;
                    AxisStatusDisps[1].ServoOnState = astatus.FlagServoOn;
                    AxisStatusDisps[1].MoveState = !astatus.FlagMoveEnd;
                    AxisStatusDisps[1].PosPrf = Math.Round(astatus.PrfPos, 3);
                    AxisStatusDisps[1].PosEnc = Math.Round(astatus.EncPos, 3);
                    //左Z轴
                    astatus = GTSCard.GetAxisStatus(gTSCard.A3);
                    AxisStatusDisps[2].AlmState = astatus.FlagAlm;
                    AxisStatusDisps[2].HomeState = astatus.FlagHome;
                    AxisStatusDisps[2].PosLimitState = astatus.FlagPosLimit;
                    AxisStatusDisps[2].NeglimitState = astatus.FlagNeglimit;
                    AxisStatusDisps[2].ServoOnState = astatus.FlagServoOn;
                    AxisStatusDisps[2].MoveState = !astatus.FlagMoveEnd;
                    AxisStatusDisps[2].PosPrf = Math.Round(astatus.PrfPos, 3);
                    AxisStatusDisps[2].PosEnc = Math.Round(astatus.EncPos, 3);
                    //右X轴
                    astatus = GTSCard.GetAxisStatus(gTSCard.A5);
                    AxisStatusDisps[3].AlmState = astatus.FlagAlm;
                    AxisStatusDisps[3].HomeState = astatus.FlagHome;
                    AxisStatusDisps[3].PosLimitState = astatus.FlagPosLimit;
                    AxisStatusDisps[3].NeglimitState = astatus.FlagNeglimit;
                    AxisStatusDisps[3].ServoOnState = astatus.FlagServoOn;
                    AxisStatusDisps[3].MoveState = !astatus.FlagMoveEnd;
                    AxisStatusDisps[3].PosPrf = Math.Round(astatus.PrfPos, 3);
                    AxisStatusDisps[3].PosEnc = Math.Round(astatus.EncPos, 3);
                    //右Y轴
                    astatus = GTSCard.GetAxisStatus(gTSCard.A6);
                    AxisStatusDisps[4].AlmState = astatus.FlagAlm;
                    AxisStatusDisps[4].HomeState = astatus.FlagHome;
                    AxisStatusDisps[4].PosLimitState = astatus.FlagPosLimit;
                    AxisStatusDisps[4].NeglimitState = astatus.FlagNeglimit;
                    AxisStatusDisps[4].ServoOnState = astatus.FlagServoOn;
                    AxisStatusDisps[4].MoveState = !astatus.FlagMoveEnd;
                    AxisStatusDisps[4].PosPrf = Math.Round(astatus.PrfPos, 3);
                    AxisStatusDisps[4].PosEnc = Math.Round(astatus.EncPos, 3);
                    //右Z轴
                    astatus = GTSCard.GetAxisStatus(gTSCard.A7);
                    AxisStatusDisps[5].AlmState = astatus.FlagAlm;
                    AxisStatusDisps[5].HomeState = astatus.FlagHome;
                    AxisStatusDisps[5].PosLimitState = astatus.FlagPosLimit;
                    AxisStatusDisps[5].NeglimitState = astatus.FlagNeglimit;
                    AxisStatusDisps[5].ServoOnState = astatus.FlagServoOn;
                    AxisStatusDisps[5].MoveState = !astatus.FlagMoveEnd;
                    AxisStatusDisps[5].PosPrf = Math.Round(astatus.PrfPos, 3);
                    AxisStatusDisps[5].PosEnc = Math.Round(astatus.EncPos, 3);

                    //IO
                    int diport1 = GTSCard.GetDiPort1(gTSCard.A1.CardNo);
                    int doPort1 = GTSCard.GetDoPort1(gTSCard.A1.CardNo);
                    for (int i = 0; i < 16; i++)
                    {
                        EXI[i] = (diport1 & (1 << i)) == 0;
                        EXO[i] = (doPort1 & (1 << i)) == 0;
                    }

                    //模拟量
                    var adcv = GTSCard.GetAdc(1);
                    LeftPowerValue = Math.Round(adcv / 4 * 1000, 0);
                    adcv = GTSCard.GetAdc(2);
                    RightPowerValue = Math.Round(adcv / 4 * 1000, 0);

                    //编码器
                    LeftAuxiliaryPosEnc = GTSCard.GetEnc(0, 9) / 1000;
                    RightAuxiliaryPosEnc = GTSCard.GetEnc(0, 10) / 1000;
                }
                catch { }
                System.Threading.Thread.Sleep(200);
            }
        }
        void LoadParam()
        {
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"));
                systemParam = JsonConvert.DeserializeObject<Param>(jsonString);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
        void SavedParam()
        {
            try
            {
                string jsonString = JsonConvert.SerializeObject(systemParam, Formatting.Indented);
                File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"), jsonString);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
   
        }
        private void JumpAction(CancellationToken token, double tartgetX, double tartgetY, double tartgetZ, AxisParm axisX, AxisParm axisY, AxisParm axisZ,double ZSafe)
        {
            try
            {


                int stepnum = 0;
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    switch (stepnum)
                    {
                        case 0://Z运动到安全位
                            {
                                GTSCard.AxisPosMove(ref axisZ, ZSafe, mzJogSpeed);
                                stepnum = 1;
                            }
                            break;
                        case 1:
                            if (GTSCard.AxisPosMoveCheckDone(axisZ))
                            {
                                stepnum = 2;
                            }
                            break;
                        case 2:
                            {
                                GTSCard.AxisPosMove(ref axisX, tartgetX, mxYJogSpeed);
                                GTSCard.AxisPosMove(ref axisY, tartgetY, mxYJogSpeed);
                                stepnum = 3;
                            }
                            break;
                        case 3:
                            if (GTSCard.AxisPosMoveCheckDone(axisX) && GTSCard.AxisPosMoveCheckDone(axisY))
                            {
                                stepnum = 4;
                            }
                            break;
                        case 4:
                            {
                                GTSCard.AxisPosMove(ref axisZ, tartgetZ, mzJogSpeed);
                                stepnum = 5;
                            }
                            break;
                        case 5:
                            if (GTSCard.AxisPosMoveCheckDone(axisZ))
                            {
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Debug.WriteLine(ex.Message);
            }
        }
        private void GoAction(CancellationToken token,double tartgetX,double tartgetY, double tartgetZ, AxisParm axisX, AxisParm axisY, AxisParm axisZ)
        {
            try
            {
                int stepnum = 0;
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    switch (stepnum)
                    {
                        case 0:
                            {
                                GTSCard.AxisPosMove(ref axisX, tartgetX, mxYJogSpeed);
                                GTSCard.AxisPosMove(ref axisY, tartgetY, mxYJogSpeed);
                                GTSCard.AxisPosMove(ref axisZ, tartgetZ, mzJogSpeed);
                                stepnum = 1;
                            }
                            break;
                        case 1:
                            if (GTSCard.AxisPosMoveCheckDone(axisX) && GTSCard.AxisPosMoveCheckDone(axisY) &&
                                GTSCard.AxisPosMoveCheckDone(axisZ))
                            {
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Debug.WriteLine(ex.Message);
            }

        }
        private void GoAction(CancellationToken token, AxisParm axisN, double tartgetN, double speed)
        {
            try
            {
                int stepnum = 0;
                Stopwatch sw = Stopwatch.StartNew();
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    switch (stepnum)
                    {
                        case 0:
                            {
                                GTSCard.AxisPosMove(ref axisN, tartgetN, speed);
                                stepnum = 1;
                            }
                            break;
                        case 1:
                            if (GTSCard.AxisPosMoveCheckDone(axisN))
                            {
                                stepnum = 2;
                            }
                            break;
                        case 2:
                            if (sw.Elapsed.TotalSeconds > 0.5)
                            {
                                sw.Stop();                                
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Debug.WriteLine(ex.Message);
            }

        }
        #endregion
    }
}
